﻿

Public Class AccountPeriod

    Property Owner As String
    Property Period As String
    Property RecordList As IEnumerable(Of Transaction) = New List(Of Transaction)

    ReadOnly Property BeginDate As String
        Get
            Return String.Format("{0}-01", Period)
        End Get
    End Property

    Property Summary As MonthlySummary

    ReadOnly Property EndDate As String
        Get
            Return Date.Parse(BeginDate).AddMonths(1).ToString("yyyy-MM-dd")
        End Get
    End Property

    ReadOnly Property JsonData As String
        Get
            Dim result As String = "NoData"
            If Me.RecordList.Count > 0 Then
                Dim list As List(Of String) = New List(Of String)
                For Each item As Transaction In Me.RecordList
                    list.Add("['" + item.Id.ToString + "','" + item.RecordDate.ToString("yyyy-MM-dd") + "','" + item.Name + "','" +
                             item.RecordType + "'," + item.Amount.ToString + ",'" + item.Payer + "','" + item.Remark + "']")
                Next
                result = String.Join(",", list)
            End If
            Return result
        End Get
    End Property

    Sub New(ByVal period As String, ByVal owner As String)

        If String.IsNullOrEmpty(period) Then
            period = Now.ToString("yyyy-MM")
        Else
            Dim temp As Date = Now
            If Date.TryParse(period, temp) Then
                period = temp.ToString("yyyy-MM")
            Else
                period = Now.ToString("yyyy-MM")
            End If
        End If

        Me.Period = period
        Me.Owner = owner
        Me.RecordList = Transaction.GetMonthlyRecord(owner, BeginDate, EndDate).ToList
        Me.Summary = MonthlySummary.FindByOwnerAndPeriod(Me.Owner, Me.Period)
    End Sub

    Function AmountByCategoryAndPayer(ByVal category As String, ByVal payer As String) As Decimal
        Return Me.RecordList.
            Where(Function(item) item.RecordType = category And (item.Payer = payer Or String.IsNullOrEmpty(payer))).
            Sum(Function(item) item.Amount)
    End Function

    Function GroupByAmountName() As Dictionary(Of String, Decimal)
        Return Me.RecordList.GroupBy(Function(item) item.Name).
            ToDictionary(Function(item) item.Key, Function(item) item.ToList.Sum(Function(record) record.Amount))
    End Function

End Class
